package com.taobao.tbk.controller;

import com.alibaba.fastjson.JSONObject;
import com.taobao.tbk.error.ErrorEnum;
import com.taobao.tbk.exception.CommonException;
import com.taobao.tbk.response.CommonResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    /**
     * 异常包装处理
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public JSONObject handleException(HttpServletRequest request, Exception exception) {
        Map<String, Object> data = new HashMap<>();
        if (exception instanceof CommonException) {
            CommonException commonException = (CommonException)exception;
            data.put("errCode", commonException.getErrCode());
            data.put("errMsg", commonException.getErrMsg());
        } else {
            data.put("errCode", ErrorEnum.UNKNOW_ERROR.getErrCode());
            data.put("errMsg", ErrorEnum.UNKNOW_ERROR.getErrMsg());
        }
        CommonResponse commonResponse = CommonResponse.create("error", data);
        JSONObject responseJsonObj = new JSONObject();
        responseJsonObj.put("error", commonResponse);
        return responseJsonObj;
    }


}
